﻿using MediatR;
using PublicCommon;
using T_Rbac.Read.APi.Application.Command.OperatetorCommand;
using T_Rbac_Demain;
using T_Rbac_Rep.Interface;

namespace T_Rbac.Read.APi.Application.Handlers.OperatorHandlers
{
    public class OperatorSearchHandler : IRequestHandler<OperatorSearchCommand, PageResult<Operator>>
    {
        private readonly IOperator ioperator;

        public OperatorSearchHandler(IOperator ioperator)
        {
            this.ioperator = ioperator;
        }

        public async Task<PageResult<Operator>> Handle(OperatorSearchCommand request, CancellationToken cancellationToken)
        {
            var list = await ioperator.GetvaluesByResult(x => x.IsDel == false);
            if (!string.IsNullOrEmpty(request.name))
            {
                list = list.Where(x => x.Oname == request.name);
            }
            if (!string.IsNullOrEmpty(request.phone))
            {
                list = list.Where(x => x.Ophone == request.phone);
            }
            if (!string.IsNullOrEmpty(request.obianhao))
            {
                list = list.Where(x => x.Onumber == request.obianhao);
            }
            if (!string.IsNullOrEmpty(request.dname))
            {
                list = list.Where(x => x.Odname == request.dname);
            }
            int listcount = list.Count();
            int pagecount = (int)Math.Ceiling(list.Count() * 1.0 / request.pagesize);
            list = list.OrderByDescending(x => x.Oid).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize);
            return await Task.FromResult(new PageResult<Operator>
            {
                List = list.ToList(),
                TotalCount = listcount,
                PageCount = pagecount,
            });
        }
    }
}
